import React, {useEffect, useState, useRef} from 'react';
import axios from "axios";
import {Card, Col, Row, Avatar, List} from 'antd';
import {EditOutlined, EllipsisOutlined, SettingOutlined} from '@ant-design/icons';
import * as echarts from 'echarts';
import _ from "lodash";

const {Meta} = Card;

export default function Home() {
    const [viewList, setViewList] = useState([])
    const [starList, setStarList] = useState([])
    // const [categoryList, setCategoryList] = useState('')

    // 方便为图表获取真正的dom节点
    const chartRef = useRef(null)

    const {username, region, role: {roleName}} = JSON.parse(localStorage.getItem('token'))

    useEffect(() => {
        // _sort：排序，_order=desc：倒序
        axios.get(`news/?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`).then(res => {
            // console.log(res.data)
            setViewList(res.data)
        })
        axios.get(`news/?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`).then(res => {
            // console.log(res.data)
            setStarList(res.data)
        })
    }, [])

    // json-server
    // 取数据  get
    // 增  post
    // 覆盖更新  put  ：将次id下之前的数据没涉及到的清除，涉及到的更新
    // 替换更新  patch  ：只替换涉及需要更新的数据
    // 删除  delete
    // _embed  :8000/posts?_embed=comments  将与 post id 相关的 comment 数据也取回来; 比如视频下的评论
    // _expand  :8000/comments?_expand=post  将与 comment 相关的 post 数据也取回来


    useEffect(() => {
            axios.get(`news/?publishState=2&_expand=category`).then(res => {
                // console.log(res.data)

                // _.groupBy 第一个参数是需要分类的数据，第二个参数是表示需要以什么来分类
                console.log((_.groupBy(res.data, item => item.category.title)))

                // 采用函数调用的方法，防止初始化过早
                renderBarView(_.groupBy(res.data, item => item.category.title))
            })

            const renderBarView = (obj) => {
                // 基于准备好的dom，初始化echarts实例
                let myChart = echarts.init(chartRef.current);

                // 监听图表容器的大小并改变图表大小
                window.onresize = function() {
                    console.log("resize")
                    myChart.resize()
                };

                // 绘制图表
                myChart.setOption({
                    title: {
                        text: '新闻栏目图示',
                        x: 'center'
                    },
                    tooltip: {},
                    legend: {
                        data: ['数量'],
                        x: 'left'
                    },
                    xAxis: {
                        data: Object.keys(obj),
                        axisTick: {
                            interval: 0
                        }
                    },
                    yAxis: {minInterval: 1},
                    series: [
                        {
                            name: '数量',
                            type: 'bar',
                            data: Object.values(obj).map(item => item.length)
                        }
                    ]
                });
            }
        }, []
    )


    return (
        <div>
            <div className="site-card-wrapper">
                <Row gutter={16}>
                    <Col span={8}>
                        <Card title="浏览量最多" bordered={true}>
                            <List
                                dataSource={viewList}
                                renderItem={item => (
                                    <List.Item>
                                        <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card title="点赞数最高" bordered={true}>
                            <List
                                dataSource={starList}
                                renderItem={item => (
                                    <List.Item>
                                        <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            cover={
                                <img
                                    alt="example"
                                    src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                                />
                            }
                            actions={[
                                <SettingOutlined key="setting"/>,
                                <EditOutlined key="edit"/>,
                                <EllipsisOutlined key="ellipsis"/>,
                            ]}
                        >
                            <Meta
                                avatar={<Avatar src="https://joeschmoe.io/api/v1/random"/>}
                                title={username}
                                description={
                                    <div>
                                        <b>{region === '' ? '全球' : region}</b>
                                        <span style={{marginLeft: '20px'}}>{roleName}</span>
                                    </div>
                                }
                            />
                        </Card>
                    </Col>
                </Row>
            </div>
            <div ref={chartRef} style={{width: '70%', height: '400px', marginTop: '50px'}}/>
        </div>
    )
}